<?php

namespace App\Models\Admin;

use App\Log\AdminMenuLog;
use Illuminate\Database\Eloquent\Model;
use DB, Auth;

class SchoolMenu extends Base
{
    const OPERATE_PID = 3;
    const MODEL = 'school_menu';

    protected $table = 'school_menu';
    protected $guarded = [];
    public $timestamps = false;

    /**
     * 表内关联
     * 获取下级菜单
     */
    public function selfNext()
    {
        return $this->hasMany($this, 'pid');
    }

    //返回所有一级和二级菜单
    public static function getMenu()
    {
        $where = [
            ['display', '=', 1]
        ];
        $nav = self::where($where)
            ->orderBy('ordid', 'asc')
            ->get()
            ->groupBy('pid');
        //获得一级菜单
        $one = $nav[0];
        //移除一级菜单
        unset($nav[0]);
        $one = $one->transform(function ($item, $key) use ($nav) {
            $item->children = isset($nav[$item->id]) ? $nav[$item->id] : [];
            return $item;
        });
        return $one;
    }

    public static function getField()
    {
        return [
            //            'id','name','short_name','pid','route','icon','dispaly',
        ];
    }

    public static function getAllList()
    {
        //        $list = self::orderBy('ordid','asc')
        $list = self::orderBy('pid', 'asc')->orderBy('ordid', 'asc')
            ->get();
        if ($list->isEmpty()) {
            return $list;
        }
        $list = self::generateTree($list);
        return $list;
    }

    public static function getDetaiById($id)
    {
        $info = self::where('id', $id)
            ->first();
        return $info;
    }

    public static function getPMenuById($id)
    {
        $path_arr = self::getPathById($id);
        if (empty($path_arr)) {
            return [];
        }
        $menu_list_1 = self::getMenuLevel();
        $pid = end($path_arr);
        array_pop($path_arr);
        $data_res['menu_list_1'] = $menu_list_1;
        if (empty($path_arr)) {
            return $data_res;
        }
        $menu_list_2 = self::getMenuLevel($pid);
        $data_res['menu_list_2'] = $menu_list_2;
        $pid = end($path_arr);
        array_pop($path_arr);
        if (empty($path_arr)) {
            return $data_res;
        }
        $menu_list_3 = self::getMenuLevel($pid);
        $data_res['menu_list_3'] = $menu_list_3;
        return $data_res;
    }

    public static function getMenuLevel($pid = 0)
    {
        $where = [
            'pid' => $pid,
        ];
        $list = self::getListByPid($where)->toArray();
        return $list;
    }

    public static function getListByPid($data)
    {
        $where = [];
        if (isset($data['pid'])) {
            $where[] = ['pid', $data['pid']];
        }
        $list = self::where($where)
            ->orderBy('ordid', 'asc')
            ->get();
        return $list;
    }

    //通过角色id，返回所有的菜单列表
    public static function getMenuByRoleId($role_id)
    {
        $menu_ids_arr = AdminCdjAuth::getMenuByRoleId($role_id);
        if ($menu_ids_arr) {
            $nav = self::whereIn('id', $menu_ids_arr)
                ->orderBy('ordid')
                ->get()->groupBy('pid');
            //获得一级菜单
            $one = $nav[0];
            //移除一级菜单
            unset($nav[0]);
            $one = $one->transform(function ($item, $key) use ($nav) {
                $item->children = isset($nav[$item->id]) ? $nav[$item->id] : [];
                return $item;
            });
            return $one;
        }
        return [];
    }

    //通过角色id，返回所有的菜单列表,授权
    public static function getAuthMenu($role_id)
    {
        $menu_auth_ids = self::menuAuthList($role_id);
        //获取当前登录用户的权限菜单
        $nav = self::select('id', 'name', 'pid')
            ->whereIn('id', $menu_auth_ids)
            //            ->whereExists(function ($query) {
            //                if (auth('admin')->user()->role_id != 1){
            //                    self::query_str($query);
            //                }
            //            })
            ->orderBy('ordid', 'asc')
            ->get()
            ->groupBy('pid');
        //获得一级菜单
        $one = $nav[0];
        //移除一级菜单
        unset($nav[0]);
        $one = $one->transform(function ($item, $key) use ($nav) {
            //            $item->selfNext = $nav[$item->id];
            $item->selfNext = isset($nav[$item->id]) ? $nav[$item->id] : collect([]);
            return $item;
        });
        return $one;
    }

    public static function menuAuthList($role_id)
    {
        if ($role_id == 1) {
            $ids = DB::table('admin_menu')->pluck('id')->toarray();
        } else {
            $ids = DB::table('admin_cdj_auth')->where('role_id', $role_id)->pluck('menu_id')->toarray();
        }
        return $ids;
    }

    private static function query_str($query)
    {
        $query->select(DB::raw(1))->from('admin_cdj_auth')
            ->whereRaw("(role_id = " . auth('admin')->user()['role_id'] . " and menu_id = " . env('DB_PREFIX') . "admin_menu.id) or (" . auth('admin')->user()['role_id'] . " = 1)");
    }

    public static function addLog($pre, $next, $type, $method = '')
    {
        $info = AdminOperateModule::where('pid', self::OPERATE_PID)->where('type', $type)->where('model', self::MODEL)->when($method, function ($query) use ($method) {
            $query->where('method', $method);
        })->first();
        if (!empty($info)) {
            $adminLog = new AdminMenuLog($pre, $next, $info);
            $adminLog->addLog();
        }
    }
}
